<?php

class Message extends CI_Controller{
function index(){
$to= $this->session->userdata('userid');
$q="select `from`,COUNT(*),`isi` from message where `to`='$to' Group By `from` ORDER BY  `tanggal` DESC";
$result=$this->db->query($q);
$sender=array();
$i=0;
foreach ($result->result_array() as $senders){
$sender[$i]['from']=$this->user->get_name($senders['from']);
$sender[$i]['count']=$senders['COUNT(*)'];
$sender[$i]['isi']=$senders['isi'];
$i++;
}
$data['senders']=$sender;
$this->load->view('message',$data);

}

function compose(){
$this->load->view('compose_msg');

}
function msg_widget(){
$to=$this->session->userdata('userid');
$query="select * from message where `to`='$to' and `status` is NULL";
$result=$this->db->query($query);
$data['count']=$result->num_rows();
$query="select * from message where `to`='$to'";
$i=0;
$msgs=array();
foreach($result->result() as $msg){
if ($i==3){
break;
}
$msgs[$i]['from']=$this->user->get_name($msg->from);
$msgs[$i]['isi']=substr($msg->isi,0,50);
$i++;
}
$data['msgs']=$msgs;

$this->load->view('msg_widget',$data);
}



function send_message($to,$message){
$from= $this->session->userdata('userid');
$t= date("YmdHis");
$q= "insert into message (`from`,`to`,`tanggal`,`isi`) values ('$from','$to','$t','$message')";
$result=$this->db->simple_query($q);
return $result;
}
function delete($id){
$q="delete from message where `id`='$id'";
$result=$this->db->simple_query($q);
return $q;
}
function read($from){
$to=$this->session->userdata('userid');
$q="update message set `status`='1' where `to`='$to' and `from`='$from'";
$this->db->query($q); 
$q="select * from message where `from`='$from'  order by `tanggal` DESC";
$result=$this->db->query($q);
$msgs= array();
$i=0;
foreach ($result->result as $msg){
$msgs[$i]['isi']=$msg->isi;
$msgs[$i]['tanggal']=$msg->tanggal;
$i++;
}
$data['msgs']=$msgs;
$this->load->view('read_msg',$data);
}


function unread_count($from){
$to=$this->session->userdata('userid');
$query="select count (*) from message where `from`='$from' and `to`='$to' and `status`='0'";
$result=$this->db->query($query);


}
}